package cn.xo68.boot.web.web;

import cn.xo68.boot.web.properties.WebCoreProperties;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.method.support.HandlerMethodReturnValueHandler;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter;
import org.springframework.web.servlet.mvc.method.annotation.RequestResponseBodyMethodProcessor;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

/**
 * 加入自定义的响应值封装处理器
 * @author wuxie
 * @date 2018-8-16
 */
@ConditionalOnProperty(prefix = "wuxie.webcore",value = "enabled-json-wapper",havingValue = "true", matchIfMissing=true)
@Configuration
public class ReturnValueHandlerInitializingAdvice implements InitializingBean {

    private final RequestMappingHandlerAdapter adapter;
    private final WebCoreProperties webCoreProperties;
    private final WebContext webContext;

    public ReturnValueHandlerInitializingAdvice(RequestMappingHandlerAdapter adapter, WebCoreProperties webCoreProperties, WebContext webContext) {
        this.adapter = adapter;
        this.webCoreProperties = webCoreProperties;
        this.webContext = webContext;
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        List<HandlerMethodReturnValueHandler> returnValueHandlers = adapter.getReturnValueHandlers();
        List<HandlerMethodReturnValueHandler> handlers = new ArrayList(returnValueHandlers);
        this.decorateHandlers(handlers);
        adapter.setReturnValueHandlers(handlers);
    }


    private void decorateHandlers(List<HandlerMethodReturnValueHandler> handlers) {

        int pos=-1;
        Iterator<HandlerMethodReturnValueHandler> iterator = handlers.iterator();
        while (iterator.hasNext()){
            HandlerMethodReturnValueHandler handler=iterator.next();
            if (handler instanceof RequestResponseBodyMethodProcessor) {
                pos = handlers.indexOf(handler);
                break;
            }
        }
        if(pos>-1){
            HandlerMethodReturnValueHandler handler=handlers.get(pos);
            JsonWrapperMethodReturnValueHandler jsonWrapperMethodReturnValueHandler=new JsonWrapperMethodReturnValueHandler((RequestResponseBodyMethodProcessor) handler);
            handlers.add(pos,jsonWrapperMethodReturnValueHandler);
        }

    }
}